var SUCCESS_CODE = 0,
	TOKEN_EXPIRED = -9,
	BUS_URL = "http://127.0.0.1:8099/";
	SSO_URL = "http://127.0.0.1:8099/";
/**
 * 获取session用户
 * @returns object
 */
function getSessionUser(){
	var user=null;
	var userStr = getSessionData('user');
	if($.trim(userStr)!=''){
		user = JSON.parse(userStr);
	}
	return user;
}
/**
 * 获取用户权限
 * @returns arrays
 */
function getUserPower(){
	var userPower=[];
	var userStr = getSessionData('userPower');
	if($.trim(userStr)!=''){
		userPower = JSON.parse(userStr);
	}
	return userPower;
}

function checkPower(funid){
	var powers = getUserPower();
	if(powers!=null){
		for(var i=0;i<powers.length;i++){
			if(powers[i].funid==funid){
				return true;
			}
		}
	}
	return false;
}

function checkPowerAndJump(funid){
	if(!checkPower(funid)){
		window.location.href="/403.html";
	}
}
/**
 * 清除session
 * @returns void
 */
function clearSession(){
	if(window.sessionStorage){
		window.sessionStorage.clear(); 
	}else{
		var cookies = document.cookie ? document.cookie.split('; ') : [];
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decodeURIComponent(parts.shift());
			if (name) {
				$.removeCookie(name);
			}
		}
	}
}

/**
 * 存储session数据
 * @param key
 * @param value
 * @returns
 */
function storeSessionData(key,value){
	if(window.sessionStorage ){
		window.sessionStorage.setItem(key, value); 
	}else{
		$.cookie(key,value,{ expires: 7, path: '/' });
	}
}
/**
 * 获取session数据
 * @param key
 * @param value
 * @returns
 */
function getSessionData(key,value){
	var value = '';
    if(window.sessionStorage ){
    	value =  window.sessionStorage.getItem(key);
	}else{
		value =  $.cookie(key);
	}
    if(key=='userToken' && $.trim(value)==''){
    	window.location.href='/login.html';
    }
    return value;
}
	
/**
 * 根据form表单序列化json对象
 * @param form
 * @returns
 */
function serializeForm(form){
	var data = {};
	$(form).serializeArray().map(function(x){
      if (data[x.name] !== undefined) {
                if (!data[x.name].push) {
                    data[x.name] = [data[x.name]];
                }
                data[x.name].push(x.value || '');
            } else {
                data[x.name] = x.value || '';
            }
     });
	return data;
}


/**
 * 发送req请求
 * @param req
 * @returns
 */
function ajaxRequest(req){
	var	ajaxConfig = $.extend(true,req.reqJSON,{});
	if(ajaxConfig['type'] == 'post' || ajaxConfig['type'] == 'put'){
		ajaxConfig['contentType'] = 'application/json;charset=utf-8';
	}
	ajaxConfig['error'] = function(data){
		try{
			var error = $.parseJSON(data.responseText);
			if(typeof error  == undefined){
				if(typeof req.afterError != undefined && typeof req.afterError=="function"){
					req.afterError(data);
				}else{
					$.messager.alert('系统异常',data.responseText);
				}
			}else if(error.code == TOKEN_EXPIRED){
				$.messager.alert('提示',"授权过期，请重新登录","info",function(){
					window.location.href='/login.html';
				});
			}else{
				if(typeof req.afterError!= undefined && typeof req.afterError=="function"){
					req.afterError(data);
				}else{
					$.messager.alert('提示',error.message);
				}
			}
		}catch(e){
			if(typeof req.afterError != undefined  && typeof req.afterError=="function"){
				req.afterError(data);
			}else{
				$.messager.alert('提示',data.responseText);
			}
		}
	};
	ajaxConfig['success'] = function(data){
		 if(data.code == TOKEN_EXPIRED){
			$.messager.alert('提示',"授权过期，请重新登录","info",function(){
				window.location.href='/login.html';
			});
		}else{
			return req.successFn(data);
		}
	};
	ajaxConfig['beforeSend'] = function(xhr) {
		if((typeof req.useToken) ==  "undefined" || req.useToken){
			xhr.setRequestHeader('Authorization',getSessionData('userToken'));
		}
	}
	$.ajax(ajaxConfig);
}


function initCommonForm(config){
	 this.formId =  config.formId;
	 this.url =  config.url;
	 this.method = config.method?config.method:"post";
	 this.useToken = config.userToken;
	 this.submitBtnId = config.submitBtnId;
	 this.successBackFunction = config.successBackFunction;
	 this.failBackFunction = config.failBackFunction;
	 this.beforeSubmitFunction = config.beforeSubmitFunction;
	 this.afterValidErrorFunction = config.afterValidErrorFunction;
	 this.showSuccessTip = (typeof config.showSuccessTip=="undefined"?true:config.showSuccessTip);
	 var obj = this;
	 $("#"+obj.submitBtnId).click(function(){
		   var flag = true;
	    	if(obj.beforeSubmitFunction && 
	    			typeof obj.beforeSubmitFunction == "function"){
			     flag = obj.beforeSubmitFunction();
	    	}else{
	    		 flag = $('#'+obj.formId).form("validate");
	    	}
	    	if(!flag){
	    		if(obj.afterValidErrorFunction && typeof obj.afterValidErrorFunction == "function"){
	    			 obj.afterValidErrorFunction();
	    		}
	    	}else{
		    	$.messager.progress({text:'提交中，请稍后...'});
	    	}
	    	if(!flag){
	    		return;
	    	}
	    	var jsonInfo = serializeForm('#'+obj.formId);
	    	var req = {useToken:obj.useToken};
			req['reqJSON'] = {
				url:  obj.url,
				type:obj.method,
				data:JSON.stringify(jsonInfo)
			};
			req['afterError']=function(data){
				 $.messager.progress('close');
				 if(obj.failBackFunction && typeof obj.failBackFunction == "function"){
	    			 obj.failBackFunction(data);
	    		}else{
	    			try{
		    			var error = $.parseJSON(data.responseText);
		    			if(typeof error  == undefined){
		    				$.messager.alert('提示',data.responseText,'error');
		    		    }else{
		    		    	if(error.status=="0"){
		 			    		$.messager.alert('提示','您已和服务器失去连接，请确定是否网络存在异常!',"info");
		 			    	}else if(error.status=="404"){
		 			    		$.messager.alert('提示','您请求的地址不存在!',"info");
		 			    	}else{
		 			    	   $.messager.alert('提示',error.message,'error');
		 			    	}
		    		    }
	    			}catch(e){
	    				 $.messager.alert('提示',data.responseText,'error');
	    			}
	    		}
			}
			req['successFn'] = function(respData){
				 $.messager.progress('close');
				 if(respData.code == SUCCESS_CODE){
						 try {
							    if(obj.successBackFunction && typeof obj.successBackFunction == "function"){
				    			 if(obj.showSuccessTip){
				    				  $.messager.show({
											title:'提示',
											msg:'操作成功',
											timeout:5000,
											showType:'slide'
										});
				    			 }
								 obj.successBackFunction(respData);
				    		}else{
							   $.messager.show({
									title:'提示',
									msg:'操作成功',
									timeout:5000,
									showType:'slide'
								});
				    		 }
						    } catch (e) {
						   }
					}else{
						
						 if(obj.failBackFunction && typeof obj.failBackFunction == "function"){
			    			 obj.failBackFunction(data);
			    		}else{
			    			$.messager.alert('提示',respData.message,'error');
			    		}
			 }
		};
		ajaxRequest(req);
  })
 return this;
}

/**
 * 获取页面传入的参数
 * @param name
 * @returns
 */
function getQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}


$(function(){
	//主动检查页面元素
	$.each($("[power]"),function(i,obj){
		var key = $(obj).attr("power");
		if(!checkPower(key)){
			$(obj).remove();
		}
	})
})

//时间戳转日期
function timeTransfoDate(time){
	var date =  new Date(time);
    var y = 1900+date.getYear();
    var m = "0"+(date.getMonth()+1);
    var d = "0"+date.getDate();
    return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
}


$(function(){
	try{
		parent.closeIndexLoading();
	}catch(e){}
})

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/**
 * 初始化combobox
 * @param item
 */
function initSel(item){
	$(item['id']).combobox({
	    url:BUS_URL+'aexginfo/queryAexginfoByType?parmType='+item['name'],
	    valueField:'parmname',
	    textField:'parmvalue',
	    method:'get',
	    beforeSend: function(request) {
		    	 request.setRequestHeader('Authorization',getSessionData('userToken'));
        }
	});
}

/**
 * 初始化系统代号 ADD页面
 */
function addSysName(id){
	$("#"+id).combobox({
	    url:BUS_URL+'asysinfo/queryAsysName',
	    valueField:'sysCode',
	    textField:'sysName',
	    method:'get',
	    beforeSend: function(request) {
		    	 request.setRequestHeader('Authorization',getSessionData('userToken'));
	    }
	});
}
/**
 * 初始化系统代号 UPD页面
 */
function updateSysName(items){
	$("#"+items['id']).combobox({
		url : BUS_URL + 'asysinfo/queryAsysName',
		valueField : 'sysCode',
		textField : 'sysName',
		method : 'get',
		beforeSend : function(request) {
			request.setRequestHeader('Authorization',
					getSessionData('userToken'));
		},
		onLoadSuccess:function(){
			$('#'+items['updId']).form('load', items['row']);
		}
	});
}
/**
 * 加载查看
 * @param formId
 * @param row
 */
function commonViewLoadForm(formId,row){
	try{
		$("#"+formId).form('load',row)
	}catch(e){}
	$.each(row,function(key,value){
		if($("#"+key).size()>0){
				try{
					$("#"+key).val(value);
				}catch(e){}
				try{
					$("#"+key).text(value);
				}catch(e){}
		}
	})
}

/**
 * 初始化机构
 * @param item
 */
function initSelRBCH(item){
	$(item['id']).combobox({
	    url:BUS_URL+'rbchinfo/queryRbch',
	    valueField:'bchId',
	    textField:'bchDesc',
	    method:'get'
	});
}


